/**
 * WebSocket杂物查询指令处理器
 * 功能：处理WebSocket指令1265，查询杂物物品
 */

const mysql = require('mysql2/promise');

// 数据库连接配置
const DB_CONFIG = {
    host: '43.143.253.188',
    port: 3306,
    user: 'nextjs',
    password: 'yEAiRE2jcxTyRBy5',
    database: 'nextjs',
    charset: 'utf8mb4'
};

class MiscItemsHandler {
    constructor() {
        this.connection = null;
    }

    // 初始化数据库连接
    async init() {
        if (!this.connection) {
            this.connection = await mysql.createConnection(DB_CONFIG);
        }
    }

    // 关闭数据库连接
    async close() {
        if (this.connection) {
            await this.connection.end();
            this.connection = null;
        }
    }

    // 定义杂物物品ID数组
    getMiscItemIds() {
        return {
            // t=3: 杂物类
            3: [71, 72, 74, 75, 108, 109],
            // t=2: 矿物类
            2: [58, 38, 48, 39, 49, 59, 60, 50, 40, 61, 41, 51, 62, 42, 52, 63, 53, 43, 54, 44, 64, 55, 45, 65, 56, 46, 66, 57, 47, 67]
        };
    }

    // 处理WebSocket指令1265
    async handleCommand1265(data) {
        try {
            const { t, pageNum = 0 } = data;

            // 验证参数
            if (typeof t !== 'number' || ![2, 3].includes(t)) {
                return {
                    act_id: 1265,
                    code: -1,
                    message: '无效的类型参数，t必须是2或3',
                    list: []
                };
            }

            // 获取对应类型的物品ID列表
            const itemIds = this.getMiscItemIds()[t];
            if (!itemIds || itemIds.length === 0) {
                return {
                    act_id: 1265,
                    code: 0,
                    list: []
                };
            }

            // 查询数据库
            const placeholders = itemIds.map(() => '?').join(',');
            const sql = `
                SELECT 
                    id,
                    name,
                    pic,
                    silver_price as price
                FROM basic_items 
                WHERE id IN (${placeholders})
                ORDER BY id
            `;

            const [rows] = await this.connection.execute(sql, itemIds);

            // 转换为标准格式
            const list = rows.map(row => ({
                id: row.id,
                name: row.name,
                pic: row.pic || 'none.png',
                price: row.price
            }));

            return {
                act_id: 1265,
                code: 0,
                list: list
            };

        } catch (error) {
            console.error('处理指令1265失败:', error.message);
            return {
                act_id: 1265,
                code: -1,
                message: '查询失败',
                list: []
            };
        }
    }

    // WebSocket消息处理器
    async handleMessage(message) {
        try {
            const data = JSON.parse(message);

            // 检查是否是指令1265
            if (data.c === 1265) {
                await this.init();
                return await this.handleCommand1265(data.d);
            }

            return null;

        } catch (error) {
            console.error('处理WebSocket消息失败:', error.message);
            return {
                act_id: 1265,
                code: -1,
                message: '消息格式错误',
                list: []
            };
        }
    }
}

// 使用示例
async function example() {
    const handler = new MiscItemsHandler();

    try {
        // 测试指令1: 查询杂物类 (t=3)
        const message1 = JSON.stringify({
            c: 1265,
            d: { t: 3, pageNum: 0 }
        });

        console.log('测试指令1 - 杂物类:');
        console.log('请求:', message1);
        const result1 = await handler.handleMessage(message1);
        console.log('响应:', JSON.stringify(result1, null, 2));

        // 测试指令2: 查询矿物类 (t=2)
        const message2 = JSON.stringify({
            c: 1265,
            d: { t: 2, pageNum: 0 }
        });

        console.log('\n测试指令2 - 矿物类:');
        console.log('请求:', message2);
        const result2 = await handler.handleMessage(message2);
        console.log('响应:', JSON.stringify(result2, null, 2));

    } finally {
        await handler.close();
    }
}

// 如果直接运行此脚本
if (require.main === module) {
    example().catch(console.error);
}

module.exports = MiscItemsHandler;
